package com.dxx.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxx.cloud.admin.mapper.ReceiveAddressMapper;
import com.dxx.cloud.admin.module.entity.ReceiveAddress;
import com.dxx.cloud.admin.service.IReceiveAddressService;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author 37048
 */
@Service
public class ReceiveAddressServiceImpl extends ServiceImpl<ReceiveAddressMapper, ReceiveAddress> implements IReceiveAddressService {
    @Override
    public List<ReceiveAddress> listByCustomerId(Long customerId) {
        if (customerId == null) {
            return null;
        }
        return list(new LambdaQueryWrapper<ReceiveAddress>().eq(ReceiveAddress::getCustomerId, customerId));
    }

    private void updateIsDefault(Long id, boolean isDefault) {
        update(new LambdaUpdateWrapper<ReceiveAddress>().eq(ReceiveAddress::getId, id).set(ReceiveAddress::getIsDefault, isDefault));
    }

    @Override
    public Boolean updateByAddress(ReceiveAddress request) {
        ReceiveAddress receiveAddress = getById(request.getId());
        if (request.getIsDefault()) {
            // 只能有一个默认地址，需要将其它地址改成非默认
            final List<ReceiveAddress> receiveAddresses = listByCustomerId(receiveAddress.getCustomerId());
            for (ReceiveAddress address : receiveAddresses) {
                if (!address.getId().equals(receiveAddress.getId())) {
                    updateIsDefault(address.getId(),false);
                }
            }
        }
        return updateById(request);
    }
}
